import constants from '@/common/constants';

export function encodeData(encodeStr: string, key = constants.ABDSUIFD) {
  let retstr = '';
  let ret;
  const strlen = encodeStr.length;
  const keylen = key.length;
  for (let i = 0; i < strlen; i++) {
    const substr = encodeStr[i];
    const subkey = key[i % keylen];
    ret = substr.charCodeAt(0) ^ subkey.charCodeAt(0);
    ret = ret !== 0 ? String.fromCodePoint(ret) : substr;
    retstr += ret;
  }
  retstr = window.btoa(unescape(encodeURIComponent(retstr)));

  retstr = encodeURIComponent(retstr);
  return retstr;
}

export function decodeData(decodeStr: string, key = constants.ABDSUIFD) {
  let ret,
    retstr = '';
  decodeStr = decodeURIComponent(decodeStr);
  decodeStr = decodeURIComponent(escape(window.atob(decodeStr)));

  const strlen = decodeStr.length;
  const keylen = key.length;
  for (let i = 0; i < strlen; i++) {
    const substr = decodeStr[i];
    const subkey = key[i % keylen];
    ret = substr.charCodeAt(0) ^ subkey.charCodeAt(0);
    ret = ret !== 0 ? String.fromCodePoint(ret) : substr;
    retstr += ret;
  }
  retstr = decodeURIComponent(retstr);
  return retstr;
}
